package com.client.rpcclient;



import com.common.entity.RPCRequest;
import com.common.entity.RPCResponse;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;

/**
 * @author Zixiang Hu
 * @description 客户端代理
 * @create 2021-03-01-14:59
 */
@Slf4j
@Builder
@AllArgsConstructor
public class RPCClientProxy implements InvocationHandler {
    private RPCClient rpcClient;

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // 构建统一请求对象
        RPCRequest request = RPCRequest.builder().requestId(UUID.randomUUID().toString())
                .interfaceName(method.getDeclaringClass().getName())
                .methodName(method.getName())
                .params(args)
                .paramsTypes(method.getParameterTypes()).build();
//        log.info("客户端请求的数据是：{}", request);
        CompletableFuture<RPCResponse> responseFuture = rpcClient.sendRequest(request);
        return responseFuture.get().getData();
    }

    public <T> T getProxy(Class<T> clazz) {
        T proxyInstance = (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz}, this);
        return proxyInstance;
    }

}
